<?php

namespace app\common\model;


use app\common\exception\ApiException;

class Banner extends BaseModel {
    public function image() {
        return $this->hasOne('Images', 'id', 'img_id')->field('id,url,from');
    }

    public function getBannerList($condition, $from = 0, $size = 8) {
        if (empty($condition['status']) && !isset($condition['status'])) {
            $condition['status'] = ['neq', config('code.status_delete')];
        }
        $order  = [
            'position_id' => 'asc',
            'id'          => 'desc'
        ];
        $result = $this->with(['image'])
            ->where($condition)
            ->order($order)
            ->limit($from, $size)
            ->select();
        if (!$result) {
            throw new ApiException('获取数据失败', 200, 1);
        }
        if (input('get.total') == 1) {
            $arr['list']  = collection($result)->hidden($this->resHidden('admin'));
            $arr['total'] = $this->where($condition)->count();
            $result       = $arr;
            return $result;
        }
        return collection($result)->hidden($this->resHidden('admin'));
    }

    public function getBanners($condition) {
        if (empty($condition['status']) && !isset($condition['status'])) {
            $condition['status'] = ['neq', config('code.status_delete')];
        }
        $order  = [
            'create_time' => 'desc',
            'id'          => 'desc'
        ];
        $result = $this->with(['image'])
            ->field('position_id,title,img_id,belong_id,cat_name')
            ->where($condition)
            ->order($order)
            ->select();
        if (!$result) {
            throw new ApiException('获取数据失败', 200, 1);
        }
        return $result;
    }

    public function saveHead($head) {

    }

    private function resHidden($type) {
        if ($type === 'admin') {
            return ['img_id', 'update_time', 'image.from'];
        }
        if ($type === 'api') {
            return ['img_id', 'update_time', 'create_time', 'image.from', 'cat_id', 'status', 'expert', 'view_count'];
        }
    }
}